<template>
    <!-- 取消激活选中时的颜色 -->
    <el-menu mode="horizontal" :ellipsis="false" class="h-[80px]">
        <img class="h-[80px]" src="@/assets/image/logo.jpg" alt="logo" />
        <div class="mr-auto leading-[80px] text-4xl">课程设计案例系统</div>
        <!-- 由于二级菜单的下拉区域是一个body的子div，设置样式时需要考虑scoped属性的作用  -->
        <!-- 设置到index.html中或全局的css文件 -->
        <!-- 或者取消当前的style中的scoped属性 -->
        <el-sub-menu index="personal" :popper-offset="0" popper-class="personal">
            <template #title>
                <img class="h-[70px] rounded-1/2" src="@/assets/image/头像.png" alt="头像" />
            </template>
            <el-menu-item @click="">个人中心</el-menu-item>
            <el-menu-item @click="toUpdatePassword">修改密码</el-menu-item>
            <el-menu-item @click="">消息中心</el-menu-item>
            <el-menu-item @click="toLogout">退出登录</el-menu-item>
        </el-sub-menu>
    </el-menu>

    <!-- 修改密码 -->
    <el-dialog v-model="dialogFormVisible" title="修改密码" draggable width="500" :before-close="toClose">
        <el-form :model="passwordForm" label-position="top" :rules="rules" ref="rulesRef">
            <el-form-item prop="oldPassword">
                <el-input type="password" show-password v-model="passwordForm.oldPassword" placeholder="请输入旧密码">
                    <template #prefix>
                        <el-icon><Lock /></el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" show-password v-model="passwordForm.password" placeholder="请输入新密码">
                    <template #prefix>
                        <el-icon><Lock /></el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="rePassword">
                <el-input type="password" show-password v-model="passwordForm.rePassword" placeholder="请确认新密码">
                    <template #prefix>
                        <el-icon><Lock /></el-icon>
                    </template>
                </el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="toSave">提交</el-button>
                <el-button type="info" plain @click="toClose">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref,reactive } from 'vue'
import { logoutRequest, updatePasswordRequest } from '@/api/user-api'
import { useRouter } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'
import { useTabsStore } from '@/stores/tabs'
import { ElMessage, ElMessageBox } from 'element-plus'

// 获取路由对象
const router = useRouter()
const permissionStore = usePermissionStore()
const tabsStore = useTabsStore()

// 修改密码表单
const dialogFormVisible = ref(false)

// 表单数据
const passwordForm = reactive({
    oldPassword: '',
    password: '',
    rePassword: ''
})

// 用户名，密码匹配规则
const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,24}$/

// 密码自定义校验
const validatePassword = (rules, value, callback) => {
    if (!pattern.test(value)) {
        callback(new Error('包含大小写字母和数字的组合，可以使用特殊字符，长度8-24个字符'))
    } else {
        callback()
    }
}

// 确认密码自定义校验
const validateRePassowrd = (rules, value, callback) => {
    if (value !== passwordForm.password) {
        callback(new Error('2次密码不一致'))
    } else {
        callback()
    }
}

// 校验规则
const rules = reactive({
    oldPassword: [
        {
            required: true,
            message: '旧密码不能为空', 
            trigger: 'blur'
        },
        // 当前存在一些老的数据，密码不符合规范，先暂时关闭这项校验
        // { 
        //     validator: validatePassword, 
        //     trigger: 'blur' 
        // }
    ],
    password: [
        { 
            validator: validatePassword, 
            trigger: 'blur' 
        }
    ],
    rePassword: [
        {
            required: true,
            message: '确认密码不能为空', 
            trigger: 'blur'
        },
        { 
            validator: validateRePassowrd, 
            trigger: 'blur' 
        }
    ]
})

// 校验结果对象
const rulesRef = ref()

// 修改密码
const toUpdatePassword = () => {
    dialogFormVisible.value = true
}

// 提交
const toSave = () => {
    updatePasswordRequest(passwordForm)
    .then(res => {
        ElMessage({
            type: res.code === 200 ? 'success' : 'error',
            message: res.msg,
        })
        if (res.code === 200) {
            afterLogout()
        }
    })
}

// 关闭
const toClose = () => {
    rulesRef.value.resetFields()
    dialogFormVisible.value = false
}

/**
 * 退出登录
 */
 const toLogout = () => {
    // 弹出一个确实提示
    ElMessageBox.confirm('确定要退出登录吗?', '确认退出',
        {
            confirmButtonText: '退出',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        logoutRequest().then(result => {
            ElMessage({
                type: 'success',
                message: '退出登录成功',
            })
        }).finally(() => {
            afterLogout()
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消退出',
        })
    })
}

/**
 * 退出登录之后，重置/清除数据，跳转回登录页
 */
const afterLogout = () => {
    // 重置存储数据
    permissionStore.resume()
    tabsStore.resume()
    // 清除本网站的一切会话存储
    sessionStorage.clear()
    // 返回登录页
    router.push('/index/login')
}
</script>

<style scoped>

</style>